import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import type { RootState } from "../../app/store";
import {
	examListBody,
	getExamHistory,
	getSubject,
	getTopic,
	subjectListBody,
} from "../../util/request";

const initialState = {
	subjectList: [] as subjectListBody[], //考试题目
	activeSubject: "", //选择的课程
	examList: [] as examListBody[], //考试记录列表
	topicList: [], //考题列表
	activeTopic: {}, //选中题目
};

export const getSubjectList = createAsyncThunk(
	"subject/getSubjectList",
	async () => {
		let res: subjectListBody[] = await getSubject();
		return res;
	}
);

export const getExamList = createAsyncThunk("subject/getExamList", async () => {
	let res: examListBody[] = await getExamHistory();
	return res;
});

export const getTopicList = createAsyncThunk(
	"subject/getTopic",
	async (id: string) => {
		let res: any = await getTopic(id);
		return res;
	}
);

export const subjectSlice = createSlice({
	name: "subject",
	initialState,
	reducers: {
		setActiveSubject: (state, action) => {
			state.activeSubject = action.payload;
		},
		setActiveTopicId: (state, action) => {
			state.activeTopic = action.payload;
		},
	},
	extraReducers: (builder) => {
		builder.addCase(getSubjectList.fulfilled, (state, action) => {
			state.subjectList = action.payload;
		});
		builder.addCase(getExamList.fulfilled, (state, action) => {
			state.examList = action.payload;
		});
		builder.addCase(getTopicList.fulfilled, (state, action) => {
			state.topicList = action.payload;
			state.activeTopic = action.payload[0];
		});
	},
});

export const { setActiveSubject, setActiveTopicId } = subjectSlice.actions;
export const selectSubjectList = (state: RootState) =>
	state.subject.subjectList;

export const selectActiveSubject = (state: RootState) =>
	state.subject.activeSubject;

export const selectExamList = (state: RootState) => state.subject.examList;

export const selectTopicList = (state: RootState) => state.subject.topicList;

export const selectActiveTopic = (state: RootState) =>
	state.subject.activeTopic;

export default subjectSlice.reducer;
